package com.jiamao.goplay.ui.discover;

import android.Manifest;
import android.content.Intent;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;

import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.adapter.NearbyAdapter;
import com.jiamao.goplay.app.AppApplication;
import com.jiamao.goplay.app.AppViewModelFactory;
import com.jiamao.goplay.base.BaseMVVMFragment;
import com.jiamao.goplay.bean.BaseRep;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.databinding.DiscoverNearbyLayoutBinding;
import com.jiamao.goplay.ui.discover.vm.NeayByVM;
import com.jiamao.goplay.util.ApmLocationUtils;
import com.jiamao.goplay.view.EmptyCallback;
import com.jiamao.goplay.view.LoadingCallback;
import com.jiamao.goplay.view.LocationErrorCallback;
import com.jiamao.goplay.view.TimeoutCallback;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.callback.SuccessCallback;
import com.kingja.loadsir.core.Convertor;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.util.DialogSettings;
import com.kongzue.dialog.v3.MessageDialog;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.tamsiree.rxkit.view.RxToast;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.socialize.PlatformConfig;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerAdapter;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.utils.SPUtils;

/**
 * 附近
 */
public class NearbyFragment extends BaseMVVMFragment<DiscoverNearbyLayoutBinding, NeayByVM> {


    private LoadService loadService;
    private boolean init = true;
    private boolean isGoToSetingsLocaltion=false;
    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, initContentView(inflater, container, savedInstanceState), container, false);
        //第二步：注册布局View
        loadService = LoadSir.getDefault().register(binding.getRoot(), new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {

                Log.d("HTML","ASDASDASDASDDSD"+   v.getId());
                if (v.getId() == R.id.ll_location_error) {
                    Messenger.getDefault().send(1, Config.MGER_LOCATION_TYPE_RECY);
                }else{
                    viewModel.getLoadInitData();
                }
                // 重新加载逻辑
            }
        },new Convertor<Integer>() {
            @Override
            public Class<? extends Callback> map(Integer httpResult) {
                Class<? extends Callback> resultCode = TimeoutCallback.class;


                switch (httpResult) {
                    case 0://成功回调
                        resultCode = SuccessCallback.class;
                        break;
                    case 1://成功回调
                        resultCode = LoadingCallback.class;
                        break;
                    case 2://成功回调
                        resultCode = TimeoutCallback.class;
                        break;
                    case 3://成功回调
                        resultCode = EmptyCallback.class;
                        break;
                    case 4:
                        resultCode = LocationErrorCallback.class;
                        break;
                }
                Log.d("HTML","resultCode: "+resultCode+" httpResult:"+httpResult);
                return resultCode;
            }
        });

        return loadService.getLoadLayout();
    }


    @Override
    public NeayByVM initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(NeayByVM.class);
    }
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return R.layout.discover_nearby_layout;
    }

    @Override
    public void onResume() {
        super.onResume();
        if(isGoToSetingsLocaltion)initRxPermissions();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        ApmLocationUtils.destroyLocation();
        Messenger.getDefault().unregister(this);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.pSwitchEvent.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer aBoolean) {
                Log.d("html","aaaaaaaaaaa"+aBoolean +" iit "+aBoolean);
                //pSwitchObservable是boolean类型的观察者,所以可以直接使用它的值改变密码开关的图标
                //if (init){
                    loadService.showWithConvertor(aBoolean);
                  //  init = false;
//                }
//                else {
               //     binding.refresh.setRefreshing(false);
//                }
            }
        });
        viewModel.uc.refreshEvent.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer aBoolean) {
                binding.refreshLayout.finishRefresh();
                binding.refreshLayout.finishLoadMore();
            }
        });


      //  loadService.showWithConvertor(httpResult);
    }

    @Override
    public void initData() {
        super.initData();
//        binding.refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                viewModel.getLoadData();
//            }
//        });
         binding.setAdapter(new NearbyAdapter(getContext()));
        //initBannView();

        Messenger.getDefault().register(this, Config.MGER_LOCATION_TYPE_RECY, Integer.class, new BindingConsumer<Integer>() {
            @Override
            public void call(Integer aMapLocation) {
                Log.d("HTML","AAAAAAAA");
                if (aMapLocation == 1){
                    isGoToSetingsLocaltion = true;
                    goIntentSetting();
                }
            }


        });
        binding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                viewModel.getLoadData(0);
            }
        });
        binding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                    viewModel.getLoadData(1);
            }
        });
        initRxPermissions();

    }

    public void initRxPermissions(){
        //请求打开相机权限
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            ApmLocationUtils.startLocation(getContext(),locationListener);
                            //RxToast.showToastShort("权限已经打开，开始获取定位");
                            //  Messenger.getDefault().send(null,Config.MGER_LOCATION_ADDR);
                        } else {
                            if (!isGoToSetingsLocaltion){
                                showLocationDialog();
                            }else {
                                isGoToSetingsLocaltion = false;
                                Messenger.getDefault().send(1,Config.MGER_LOCATION_TYPE);
                            }
                         //   RxToast.showToastShort("定位权限被拒绝");
                        }
                    }
                });
    }




    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                Messenger.getDefault().send(location,Config.MGER_LOCATION_ADDR);
                ApmLocationUtils.stopLocation();
                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if(location.getErrorCode() == 0){

                  //  LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());

                    AppApplication.getInstance().lat = location.getLatitude();
                    AppApplication.getInstance().lot = location.getLongitude();

                    SPUtils.getInstance().put("lat",(float) location.getLatitude());
                    SPUtils.getInstance().put("lot",(float)location.getLongitude());

                    sb.append("定位成功" + "\n");
                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    sb.append("提供者    : " + location.getProvider() + "\n");

                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                    sb.append("角    度    : " + location.getBearing() + "\n");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("星    数    : " + location.getSatellites() + "\n");
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + location.getAdCode() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                    sb.append("兴趣点    : " + location.getPoiName() + "\n");
                    //定位完成的时间
                    // sb.append("定位时间: " + Utils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");

                     viewModel.addLocation(location);
                } else {
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
                }
                //解析定位结果，
                String result = sb.toString();
                Log.d("HTML","ADDR:"+result);

                //   tvResult.setText(result);
            } else {
                //   tvResult.setText("定位失败，loc is null");
            }

        }
    };

    private void goIntentSetting() {
        isGoToSetingsLocaltion = true;
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getContext().getPackageName(), null);
        intent.setData(uri);
        try {
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void showLocationDialog(){

        MessageDialog.build((AppCompatActivity) getActivity())
                .setStyle(DialogSettings.STYLE.STYLE_IOS)
                .setTitle("无法获取您的位置")
                .setMessage("无法获取您的位置！无法获取您的位置无法获取您的位置")
                .setOkButton("去设置", new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        goIntentSetting();
                        return false;
                    }

                }).setCancelButton("取消", new OnDialogButtonClickListener() {
            @Override
            public boolean onClick(BaseDialog baseDialog, View v) {
                Messenger.getDefault().send(1,Config.MGER_LOCATION_TYPE);
                return false;
            }
        })
                .show();

    }


}
